<template>
	<div>
		<template>
			<el-tree :props="props" :load="loadNode" lazy show-checkbox></el-tree>
		</template>
	</div>
</template>

<script>
import { getTreeMenu, toTreeData } from '@/APIs/index/index'
export default {
	data() {
		return {
			props: {
				label: 'name',
				children: 'zones',
				isLeaf: 'leaf'
			}
		}
	},
	methods: {
		loadNode(node, resolve) {
			// 展开第一级节点，从后台加载一级节点列表
			if (node.level == 0) {
				this.loadfirstnode(resolve)
			}
			// 展开其它级节点，动态从后台加载下一级节点列表
			if (node.level >= 1) {
				this.loadchildnode(node, resolve)
			}
		},
		// 获取第一级节点
		loadfirstNode(resolve) {
			this.api({ url: 'url' }).then(data => {
				return resolve(data.list)
			})
		},
		// 获取子节点集合
		loadchildNode(node, resolve) {
			this.api({ url: 'url', params: { id: node.data.id } }).then(data => {
				return resolve(data.list)
			})
		},
		//树形列表
		getTreeData() {
			getTreeMenu('').then(res => {
				this.loading = false
				let treeList = res.result
				const userStr = JSON.parse(treeList) //从一个字符串中解析出json对象
				this.treeData = toTreeData(userStr, 'id', 'pId', 'name')
				//this.chils = JSON.stringify(result, null, '\t');//从一个对象解析出字符串
			})
		},
		// 调用子节点方法,参数为父节点的数组
		children(parent) {
			// console.log(parent)
			if (data.length !== 0) {
				for (let i = 0; i < parent.length; i++) {
					for (let j = 0; j < data.length; j++) {
						if (parent[i].id == data[j][pid]){
							let obj = {
								label: data[j][name],
								id: data[j][id],
								children: []
							};
							parent[i].children.push(obj);
						}
					}
					children(parent[i].children);
				}
			}
		}
		return parent
	}
}
</script>
